local key = KEYS[1] -- 商品的键名 (hash名)
local amount = tonumber(ARGV[1]) -- 扣减的数量
local bookid = ARGV[2] -- map 的key (hash中的字段名)

-- 记录日志，安装默认的log级别为NOTICE
redis.log(redis.LOG_NOTICE, "Received the key: " .. key)
redis.log(redis.LOG_NOTICE, "Received the amount: " .. amount)
redis.log(redis.LOG_NOTICE, "Received the bookid: " .. bookid)

-- 获取商品当前的库存量
local stock = tonumber(redis.call('hget', key, bookid))
redis.log(redis.LOG_NOTICE, "Current stock: " .. (stock or "nil"))

-- 检查库存是否足够
if stock == nil then
    return "BOOKID_NOT_FOUND"
elseif stock >= amount then
    -- 扣减库存
    redis.call('hincrby', key, bookid, -amount)
    local new_stock = tonumber(redis.call('hget', key, bookid))
    redis.log(redis.LOG_NOTICE, "New stock: " .. new_stock)
    return tostring(new_stock)
else
    return "INSUFFICIENT_STOCK"
end
